package com.gadarts.parashoot.utils;

import java.lang.reflect.Field;

import android.content.Context;
import android.graphics.Rect;
import android.util.TypedValue;

import com.gadarts.parashoot.GameObject;
import com.gadarts.parashoot.Sprite;

public class ViewUtils {

	// Convert pixels to density-independent pixels.
	public final static int calculatePosX(int theX, int currentWidth) {
		float x = (float) theX;
		float width = (float) currentWidth;
		
		// Calculate the percentage of position.
		float posRatio = x * (100f) / C.DEF_WIDTH;
		
		return (Math.round(posRatio * width / 100f));
	}

	public final static int calculatePosY(int theY, int currentHeight) {
		float y = (float) theY;
		float height = (float) currentHeight;
		float posRatio = y * (100f) / C.DEF_HEIGHT;// Calculate the percentage
													// of position.
		return (Math.round(posRatio * height / 100f));
	}

	// Convert pixels to text DPI.
	public static float calculateTextSize(Context context, int size) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				size, context.getResources().getDisplayMetrics());
	}

	// Flips through the frames.
	public static int animate(Sprite sprite, int currentFrame,
			boolean loop) {
		if (currentFrame != sprite.size() - 1) {
			return ++currentFrame;
		}
		return loop ? 0 : currentFrame;
		
	}

	// Returns the ID integer of a resource.
	public static int getResId(String variableName, Class<?> c) {
		try {
			Field idField = c.getDeclaredField(variableName);
			return idField.getInt(idField);
		} catch (Exception e) {
			Utils.log(variableName);
			e.printStackTrace();
			return -1;
		}
	}

	// Checks whether the object touches this position.
	public static boolean checkCollision(GameObject object, int x, int y) {
		if (x >= object.getX() && x < object.getX() + object.getWidth())
			if (y >= object.getY() && y < object.getY() + object.getHeight())
				return true;
		return false;
	}
	
	// Checks whether the point is in the given rectangle.
	public static boolean checkCollisionPartial(Rect rect, int x, int y) {
		if(rect.contains(x, y))
				return true;
		return false;
	}
}
